import './WijmoPivotPanel.scss'
import { v4 } from 'uuid'
import { useState } from 'react'
import { Menu, Button, Popover, Input } from 'antd'
import { PivotPanel } from '@grapecity/wijmo.react.olap'
import { useMount, useLocalStorageState } from 'ahooks'

const WijmoPivotPanel = ({ data, ModalEvent }) => {
    const { itemsSource, combination, initCom } = data
    const [Combination, setCombination] = useLocalStorageState('Combination')
    const [Value, setValue] = useState()
    const [Open, setOpen] = useState(false)
    const [ComList, setComList] = useState([])
    const [DefaultKey, setDefaultKey] = useState(initCom)
    // 获取表的预设设置 / 获取用户的预设设置

    const onClick = ({ key }) => {
        setDefaultKey(key)
        ModalEvent.emit({ type: 'SwitchGrouping', data: key })
    }

    const onAdded = () => {
        const key = v4()
        const item = { key, label: Value }
        const obj = { key, title: Value, data: itemsSource.viewDefinition }
        if (!Combination) {
            setCombination([obj])
            const items = { key: 2, label: '本地组合', type: 'group', children: [item] }
            ComList.push(items)
            setComList([...ComList])
        } else {
            const data = [...Combination, obj]
            ComList[1].children.push(item)
            setComList([...ComList])
            setCombination(data)
        }
        setValue('')
        setOpen(false)
        setDefaultKey(key)
    }


    useMount(() => {
        const data = Object.keys(combination).map(key => ({ key, label: combination[key].title }))
        const items = [{ key: 1, label: '公用组合', type: 'group', children: data }]
        if (Combination) {
            const arr = Combination.map(({ key, title }) => ({ key: key, label: title }))
            const loca = { key: 2, label: '本地组合', type: 'group', children: arr }
            items.push(loca)
        }
        setComList(items)
    })

    const Content = (
        <div className='WijmoPivotPanelAdd'>
            <Input placeholder='请输入新组合名称' value={Value} onChange={e => setValue(e.target.value)} />
            <Button size='small' type='primary' onClick={onAdded}>确认</Button>
        </div>
    )

    return (
        <div className='WijmoPivotPanel'>
            <div className='Left'>
                <PivotPanel itemsSource={itemsSource} />
            </div>
            <div className='Right'>
                <Menu
                    selectedKeys={[DefaultKey]}
                    onClick={onClick}
                    mode="inline"
                    items={ComList}
                />
                <Popover
                    open={Open}
                    content={Content}
                    title="请为新组合命名!"
                    onOpenChange={setOpen}
                >
                    <Button type='primary' block>保存新组合</Button>
                </Popover>
            </div>
        </div>
    )
}

export default WijmoPivotPanel;